import tkinter as tk
import colorsys

class ColorSliderApp:
    def __init__(self, root):
        self.root = root
        self.root.title("颜色空间控制器")
        
        # 初始化变量
        self.r = tk.IntVar(value=128)
        self.g = tk.IntVar(value=128)
        self.b = tk.IntVar(value=128)
        self.h = tk.IntVar(value=180)
        self.s = tk.IntVar(value=50)
        self.v = tk.IntVar(value=50)
        
        self.updating = False  # 防止更新循环
        
        # 创建界面
        self.create_widgets()
        self.update_color()

    def create_widgets(self):
        # 颜色显示区域
        self.canvas = tk.Canvas(self.root, width=200, height=200, bg='#808080')
        self.canvas.grid(row=0, column=3, rowspan=1, padx=10, pady=5)

        # RGB滑块
        self.create_slider("R", 0, 255, self.r, 0, self.update_rgb)
        self.create_slider("G", 0, 255, self.g, 1, self.update_rgb)
        self.create_slider("B", 0, 255, self.b, 2, self.update_rgb)
        
        # HSV滑块
        self.create_slider("H", 0, 360, self.h, 4, self.update_hsv)
        self.create_slider("S", 0, 100, self.s, 5, self.update_hsv)
        self.create_slider("V", 0, 100, self.v, 6, self.update_hsv)
        
        self.text = tk.Text(self.root, width=9, height=1)
        self.text.grid(row=1, column=3, padx=10, pady=5)

    def create_slider(self, label, from_, to, var, column, command):
        frame = tk.Frame(self.root)
        frame.grid(row=0, column=column, padx=5)
        tk.Label(frame, text=label).pack()
        tk.Scale(frame, from_=from_, to=to, variable=var, 
                orient=tk.VERTICAL, length=200,
                command=lambda _: command()).pack()

    def update_rgb(self):
        if self.updating: return
        self.updating = True
        
        # 转换RGB到HSV
        r, g, b = [v.get()/255 for v in (self.r, self.g, self.b)]
        h, s, v = colorsys.rgb_to_hsv(r, g, b)
        
        self.h.set(round(h*360))
        self.s.set(round(s*100))
        self.v.set(round(v*100))
        
        self.update_color()
        self.updating = False

    def update_hsv(self):
        if self.updating: return
        self.updating = True
        
        # 转换HSV到RGB
        h, s, v = [self.h.get()/360, self.s.get()/100, self.v.get()/100]
        r, g, b = colorsys.hsv_to_rgb(h, s, v)
        
        self.r.set(round(r*255))
        self.g.set(round(g*255))
        self.b.set(round(b*255))
        
        self.update_color()
        self.updating = False

    def update_color(self):
        color = "{:02x}{:02x}{:02x}".format(self.r.get(), self.g.get(), self.b.get())
        self.canvas.config(bg="#"+color)
        self.text.delete(1.0, tk.END)
        self.text.insert(tk.END, "#"+color)

if __name__ == "__main__":
    root = tk.Tk()
    app = ColorSliderApp(root)
    root.mainloop()